<?php
/**
 * Created by PhpStorm.
 * User: 陈立强
 * Date: 2019/9/9
 * Time: 9:22
 */
/**
 * 商家
 * @author maniac
 */
namespace app\common\service;

use app\common\model\GoodCategory;
use app\common\model\Goods;
use app\common\model\Stores AS StoresModel;
use app\common\model\Zoning as ZoningModel;
use app\common\model\Members AS MembersModel;
use app\common\model\MemberYongjin AS MemberYongjinModel;
use app\common\model\ShopType AS ShopTypeModel;
use app\common\model\MemberCash AS MemberCashModel;
use app\facade\Options AS OptionsFacade;

class Stores extends Base
{

    /**
     * 门店列表
     */
    public static function Stores($where, $limit = '', $order = 'list_order DESC,id DESC',$field='',$arg =array())
    {
        $field = $field ?: 'id,uid,contact_name,name,discount,salecount,image_uri,photos,phone,content,idcard_id,list_order,delete_time,deposit,balance,totalamount,status,province,city,district,bank_name,bank_num,bank_cnname,email,fax,address,detail,read_num,enquiry_num,pic,pic_url,category_id,type_id,is_flag,zhuying,pic pic_id,image_uri image_uri_id,photos photos_ids';

        $append_arr=['pic','idcard_pic','category_name','type_name','region','image_uri','photos'];
        if(empty($arg['lng']) && empty($arg['lat'])){
            $field.=",0 distance";


            $list =StoresModel::field($field)->where($where)->append($append_arr)->order($order)->limit($limit)->select()->toArray();
        }else{

            $field=$field.",(ROUND(6378.138*2*ASIN(SQRT(POW(SIN((" . $arg['lng'] . "*PI()/180-lng  *PI()/180)/2),2)+COS(" . $arg['lng'] . "*PI()/180)*COS(lng*PI()/180)*POW(SIN((" . $arg['lat'] . "*PI()/180-lat*PI()/180)/2),2)))*1000))/1000 AS distance";
            $list=StoresModel::field($field)->where($where)->where($arg['where_rt_a'])->where($arg['where_rt_b'])->order($order)->append($append_arr)->limit($limit)->select()->toArray();
        }

        return $list;
    }

    /**
     * 获取店铺详情
     * * @param array  $where 查询条件
     */
    public function detail($where,$field='',$append=array(),$arg=array())
    {
        $field = $field ?: "id,uid,balance,name,idcard_txt,idcard_id,phone,pic,enddt,startdt,contact_name,category_id,type_id,province,city,district,address,address_txt,lng,lat,image_uri,photos,discount,zhuying,hj_pic,content,pic pic_id,image_uri image_uri_id,photos photos_ids,hj_pic hj_pic_ids";
		if($arg){
			$str_field=$field.",(ROUND(6378.138*2*ASIN(SQRT(POW(SIN((" . $arg['lng'] . "*PI()/180-lng  *PI()/180)/2),2)+COS(" . $arg['lng'] . "*PI()/180)*COS(lng*PI()/180)*POW(SIN((" . $arg['lat'] . "*PI()/180-lat*PI()/180)/2),2)))*1000))/1000 AS distance";
		}else{
			$str_field=$field;
		}


        $append=!empty($append)?$append:['pic','idcard_pic','category_name','type_name','region','image_uri','photos','hj'];

        $info=StoresModel::field($str_field)->where('id',$where)->append($append)->find();

        return $info;
    }

    /**
     * 注册商家
     * * @param array  $where 查询条件
     */
    public function add($post)
    {

        $where = [];
        // 添加店铺信息
        $data = [
            'parent_id'=>isset($post['shop_id'])?$post['shop_id']:0,
            'category_id'=>$post['category_id'],
            'type_id' => isset($post['type_id'])?$post['type_id']:'',
            'uid' => $post['userid'],
            'name' => $post['name'],
            'contact_name'=>isset($post['contact_name'])?$post['contact_name']:'',
            'idcard_txt'=>isset($post['idcard_txt'])?$post['idcard_txt']:'',
            'idcard_id'=>isset($post['idcard_id'])?$post['idcard_id']:'',
            'pic'=>isset($post['pic'])?$post['pic']:'',
            'province' => isset($post['province'])?$post['province']:'',
            'city' => isset($post['city'])?$post['city']:'',
            'district'=>isset($post['district'])?$post['district']:'',
            'address'=>isset($post['address'])?$post['address']:'',
            'address_txt'=>isset($post['address_txt'])?$post['address_txt']:'',
            'lng'=>isset($post['lng'])?$post['lng']:'',
            'lat'=>isset($post['lat'])?$post['lat']:'',
        ];
        if(isset($post['id']) && $post['id']>0){
            $shops=StoresModel::field(true)->where('id',$post['id'])->update($data);
        }else{
            $shops = StoresModel::create($data);
        }
        return $shops;
    }

    /**
     * 获取三级联动
     *
     */
    public function linkage()
    {
        $wherea = [
            'region_type' => 1,
        ];

        $data = ZoningModel::field('region_id,region_name as name')->where($wherea)->select()->toArray();

        foreach ($data as $key => $val){
            $where = [
                'parent_id' => $val['region_id'],
            ];

            $data_city = ZoningModel::field('region_id,region_name as name')->where($where)->select()->toArray();
            foreach ($data_city as $k => $v){
                $wheres = [
                    'parent_id' => $v['region_id'],
                ];

                $data_district = ZoningModel::field('region_id,region_name as name')->where($wheres)->select()->toArray();
                $data_city[$k]['sub'] = $data_district;
            }
            $data[$key]['sub'] = $data_city;
        }

        return $data;
    }


    /**
     * 我的余额明细
     * @param int $uid  用户编号
     * @param string $limit  分页条件
     */
    public function balance($uid, $limit,$type)
    {
        $where = [];
        if($type >0){
            $where['type'] = $type;
        }

        $info = MemberYongjinModel::field(true)
            ->where('shop_id', $uid)
            ->where($where)
            ->order('id desc')
            ->limit($limit)
            ->select()->toArray();
        return $info;
    }


    /**
     * 申请提现
     * @param int $userId 申请会员
     * @param object $post 提现信息
     */
    public function cash($userId, $post)
    {
        $money = (float)$post['money'];
        if (!$money) {
            exception('请输入提现金额');
        }
        $member = StoresModel::field('id,balance')->where('id', $userId)->find();

        if ($money > $member['balance']) {
            exception('提现金额不足');
        }
        $create = [
            'shop_id' => $userId,
            'money' => $money,
            'card_no' => $post['card_no'],
            'bank' => isset($post['bank'])?$post['bank']:'',
            'name' => isset($post['name'])?$post['name']:'',
            'mobile' => $post['mobile'],
            'type'=>$post['type'],
            'sy_money'=>$member['balance']- $money,
            'title'=>'商家提现'
        ];

        $info = MemberCashModel::create($create);

        if ($info) {

            $member->balance = $member['balance'] - $money;

            if ($member->save()) {

                return true;

            }

        }

        return false;

    }

    /**
     * 提现记录
     * @param int $userId 申请会员
     * @param string $limit 分页条件
     */
    public function cashRecord($userId, $limit)
    {
        $cash_list = MemberCashModel::field('apply_time,money,sy_money,status')
            ->where(['shop_id' => $userId])->fetchSql(false)
            ->limit($limit)
            ->select()->toArray();
        foreach ($cash_list as &$v) {
            $v['apply_time'] = date("Y-m-d H:i:s", $v['apply_time']);

            if ($v['status'] == 1) {
                $v['status_txt'] = '提现成功';
            } elseif ($v['status'] == 2) {
                $v['status_txt'] = '提现失败';
            } else {
                $v['status_txt'] = '提现中';
            }
        }

        return $cash_list;

    }

    /**
     * @param $uid
     * 生成二维码图片
     */
    public function generateQrCode($temp){
        $access_token=\app\facade\Wechat::getAccessToken();
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$access_token;
        $url_path="?shop_id={$temp['id']}&shop_name={$temp['shop_name']}";
        $param = $this->decodeUnicode(json_encode(array("path"=>$url_path,"width"=> 150)));

        //生成二维码
        $url="/static/uploads/qrcode/".$temp['id'].".jpg";
        $qrcode_img = $_SERVER['DOCUMENT_ROOT'].$url;


        //POST参数
        $result =$this->httpRequest( $qcode, $param,"POST");
        file_put_contents($qrcode_img, $result);

        $options = unserialize(OptionsFacade::option('site_info'));
        $url=$options['site_url'].$url;
        return $url;
    }

    public function decodeUnicode($str)
    {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
            create_function(
                '$matches',
                'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
            ),
            $str);
    }

    /**
     * 发送请求
     */
    public function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /*门店*/
    public function shop_list($parent_id,$limit){
        return StoresModel::field('id,name,uid,contact_name')->where('parent_id',$parent_id)->order('id desc')->limit($limit)->select()->toArray();

    }

    /*添加商品分类*/
    public function add_category($arg){
        if(!empty($arg['id'])){
            return GoodCategory::field(true)->where('id',$arg['id'])->update(['name'=>$arg['name']]);

        }else{
            $temp=array(
                'store_id'=>$arg['store_id'],
                'name'=>$arg['name'],
                'create_time'=>time(),
                'is_show'=>1,
                'is_last'=>1
            );
            return GoodCategory::field(true)->insert($temp);
        }
    }

    /*分类列表*/
    public function category_list($shop_id){
        return GoodCategory::field(true)->where('store_id',$shop_id)->where('delete_time',0)->fetchSql(false)->select();

    }

    /*分类删除*/
    public function category_del($id){
        return GoodCategory::field(true)->where('id',$id)->fetchSql(false)->update(['delete_time'=>time()]);

    }

    /*添加商品*/
    public function add_product($arg){
        $goods_album = [];
        $content_pic=[];

        if (isset($arg['goods_album']) && !empty($arg['goods_album'])) {
            $goods_album_arr=explode(',',$arg['goods_album']);
            foreach($goods_album_arr as $k=>$v){
                $goods_album_arr['desc'][]=$v;
                $goods_album_arr['value'][]=$v;
            }

            foreach ($goods_album_arr['desc'] as $key => $val) {
                $goods_album[$key] = [
                    'value' => $goods_album_arr['value'][$key],
                    'desc'  => $val,
                ];
            }
        }

        if (isset($arg['content_pic']) && !empty($arg['content_pic'])) {
            $content_pic_arr=explode(',',$arg['content_pic']);
            foreach($content_pic_arr as $k=>$v){
                $content_pic_arr['desc'][]=$v;
                $content_pic_arr['value'][]=$v;
            }

            foreach ($content_pic_arr['desc'] as $key => $val) {
                $content_pic[$key] = [
                    'value' => $content_pic_arr['value'][$key],
                    'desc'  => $val,
                ];
            }
        }


        $temp=array(
            'store_id'=>$arg['store_id'],
            'category_id'=>$arg['category_id'],
            'goods_name'=>$arg['goods_name'],
            'sale_price'=>$arg['sale_price'],
            'goods_thumb_id'=>$arg['goods_thumb_id'],
            'create_time'=>time(),
            'is_sale'=>1,
            'goods_intro'=>$arg['goods_intro'],
            'goods_album'=>serialize($goods_album),
            'content_pic'=>serialize($content_pic)
        );
        if(!empty($arg['id'])){
            return Goods::field(true)->where('id',$arg['id'])->update($temp);

        }else{

            return Goods::field(true)->insert($temp);
        }
    }

    /*产品列表*/
    public function product_list($shop_id,$category_id=0,$limit){
        $where=[];
        if($category_id){
            $where=[
                ['category_id','eq',$category_id]
            ];
        }
        return Goods::field(true)->where('store_id',$shop_id)->append(['image_uri'])->where($where)->order('id desc')->limit($limit)->select()->toArray();

    }

    /*产品删除*/
    public function product_del($id){
        return Goods::field(true)->where('id',$id)->fetchSql(false)->update(['delete_time'=>time()]);

    }

    /*商品详情*/
    public function product_detail($id){
        return Goods::field("id,store_id,category_id,goods_name,sale_price,goods_thumb_id,goods_album,content_pic,goods_intro,create_time,is_sale,sale_time")->append(['product_name','sale_price','image_uri', 'goods_album_detail', 'content_pic_detail', 'is_sale_txt', 'sale_time_txt','shop_txt'])->where('id',$id)->find();

    }

    /**
     * 获取绑定银行卡信息
     */
    public function getBandData($userid,$type){

        $where=[
            ['shop_id','eq',$userid],
            ['type','eq',$type]
        ];
        return MemberCashModel::where($where)->field('card_no,bank,mobile,name')->order('id desc')->limit(1)->select();
    }

    /**
     *门店下分类
     * @param 一级分类
     * @param 二级分类
     */
    public function getTypeList($category_id,$type_id){

        $sub_list=[];
        if($type_id){
            $sub_where=[
                ['id','in',$type_id]
            ];
            $sub_list=ShopTypeModel::where($sub_where)->field('id,parent_id,name')->select()->toArray();
        }

        $where=[
            ['id','in',$category_id]
        ];
        $list=ShopTypeModel::where($where)->field('id,parent_id,name,"" sub_list')->select()->toArray();

        foreach ($list as $k=>$v){
            $list[$k]['sub_list']=[];
            foreach ($sub_list as $sv){
                if($v['id']==$sv['parent_id']){
                    $list[$k]['sub_list'][]=$sv;
                }
            }
        }

        return $list;

    }
}
